package com.financing.wap.web.controller.api;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.financing.mail.dto.MailContentDTO;
import com.financing.mail.service.MailSenderService;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.FpBiddingReceiptDTO;
import com.financing.wap.dto.ProductDetailPageDTO;
import com.financing.wap.dto.UserDTO;
import com.financing.wap.service.IFpBiddingReceiptService;
import com.financing.wap.service.IProductService;
import com.financing.wap.service.ISmsNewService;
import com.financing.wap.util.CallJavaScriptUtil;
import com.financing.wap.util.Constants;
import com.financing.wap.util.DTOdateSetUtil;
import com.financing.wap.util.PropertiesUtils;
import com.financing.wap.util.SequenceManagerNew;
import com.financing.wap.vo.ProductProfitAndRebateVO;
import com.financing.wap.web.controller.BaseController;

/**
 * 

* @ClassName: BiddingReceiptController

* @Description: 产品竞价

* @author A18ccms a18ccms_gmail_com

* @date 2016-4-14 下午4:26:13

*
 */
@Controller("biddingReceiptController")
@RequestMapping("/api/biddingReceipt")
public class BiddingReceiptController extends BaseController {
	
	Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	IProductService productService;
	
	@Autowired
	IFpBiddingReceiptService fpBiddingReceiptService;
	
	String biddingProductPhoneTo=PropertiesUtils.getValue("biddingProduct.phone.to");

	String biddingProductEmailTo=PropertiesUtils.getValue("biddingProduct.email.send.to");
	String biddingProductEmailCopyTo=PropertiesUtils.getValue("biddingProduct.email.send.copy.to");
	@Autowired
	public ISmsNewService smsNewService;
	
	@Resource(name="EmailSendServiceImp")
	private MailSenderService mailSenderService;
	/**
	 * 查询竞价收单差价
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/queryBiddingReceiptChajia")
	@ResponseBody
	public ResultMap queryBiddingReceiptChajia(HttpServletRequest request,
			HttpServletResponse response,
			FpBiddingReceiptDTO fpBiddingReceiptDto, String json) {
		ResultMap result = new ResultMap();

		logger.info("In queryBiddingReceipt Begin");
		String platformtype = request.getParameter(Constants._PT);
		if (StringUtils.isBlank(platformtype)) {
			platformtype = "pc";// 默认认为pc
		}
		fpBiddingReceiptDto.setSrouce(platformtype);
		try {
			// 参数过滤
			if (fpBiddingReceiptDto.getpId() == 0 || StringUtils.isBlank(json)) {
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			JSONArray jsonArray = null;
			try {
				jsonArray = JSONArray.parseArray(json);
			} catch (Exception e) {
				logger.error("queryBiddingReceipt get jsonArray error");
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			// 查询产品是否存在
			ProductDetailPageDTO productDetailView = productService
					.getProductDetailView(fpBiddingReceiptDto.getpId());
			//竞价校验
			BiddingValidate(fpBiddingReceiptDto, jsonArray, result,productDetailView);
			
			//校验不通过  直接返回
			if(STATUS.ERROR.equals(result.getStatus())){
				return result;
			}
			
			
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			log.error(" queryBiddingReceipt error!", e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;
	}
	/**
	 * 查询当前用户是否有该产品竞价收单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/queryOldBiddingReceipt")
	@ResponseBody
	public ResultMap queryOldBiddingReceipt(HttpServletRequest request,
			HttpServletResponse response,
			FpBiddingReceiptDTO fpBiddingReceiptDto) {
		ResultMap result = new ResultMap();
		
		try {
			
			UserDTO user=SessionUtil.getSession().getUser();
			
			if(user==null||user.getId()==null){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.LOGIN_NOLOGIN_ERROR);
				return result;
			}
			// 参数过滤
			int biddingReceiptId = fpBiddingReceiptDto.getpId();
			if (biddingReceiptId == 0) {
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			//查询用户是否已经有过该产品竞价
			// 查询产品 竞价 收益
			FpBiddingReceiptDTO oldBidding = new FpBiddingReceiptDTO();
			oldBidding.setpId(biddingReceiptId);
			oldBidding.setBiddingStatus("1");
			oldBidding.setFaId(user.getId());
			List<Map<String, Object>> oldBiddingList = fpBiddingReceiptService
					.queryFpBiddingReceipt(oldBidding);
			if(oldBiddingList!=null&&oldBiddingList.size()>0){
				result.setAttribute("flagOldBidding", true);
			}else{
				result.setAttribute("flagOldBidding", false);
			}
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			log.error(" queryOldBiddingReceipt error!", e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 添加竞价收单
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/addBiddingReceipt")
	@ResponseBody
	public ResultMap addBiddingReceipt(HttpServletRequest request,
			HttpServletResponse response,
			FpBiddingReceiptDTO fpBiddingReceiptDto, String json) {
		ResultMap result = new ResultMap();

		logger.info("In addBiddingReceipt Begin");

		String platformtype = request.getParameter(Constants._PT);
		if (StringUtils.isBlank(platformtype)) {
			platformtype = "pc";// 默认认为pc
		}
		fpBiddingReceiptDto.setSrouce(platformtype);
		try {
			// 参数过滤
			int pId = fpBiddingReceiptDto.getpId();
			if (pId == 0 || StringUtils.isBlank(json)) {
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			JSONArray jsonArray = null;
			try {
				jsonArray = JSONArray.parseArray(json);
			} catch (Exception e) {
				logger.error("addBiddingReceipt get jsonArray error");
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}
			// 查询产品是否存在
			ProductDetailPageDTO productDetailView = productService
					.getProductDetailView(pId);
			
			//竞价校验
			BiddingValidate(fpBiddingReceiptDto, jsonArray,result,productDetailView);
			
			//校验不通过  直接返回
			if(STATUS.ERROR.equals(result.getStatus())){
				return result;
			}
			
			String bzj=SequenceManagerNew.seq_bzj();
			fpBiddingReceiptDto.setBiddingCode(bzj);
			//新增
			int receiptId=fpBiddingReceiptService.addFpBiddingReceiptBatch(jsonArray, fpBiddingReceiptDto);
			
			result.setAttribute("biddingCode", bzj);
			result.setAttribute("biddingReceiptId", receiptId);
			result.setStatus(ResultMap.STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);

		} catch (Exception e) {
			log.error(" addBiddingReceipt error!", e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		logger.info("In addBiddingReceipt  end");
		return result;
	}
	
	/***
	 * 
	
	* @Title: BiddingValidate
	
	* @Description: 校验竞价
	
	* @param @param fpBiddingReceiptDto
	* @param @param json
	* @param @param result
	* @param @throws Exception    设定文件
	
	* @return void    返回类型
	
	* @throws
	 */
	public void BiddingValidate(FpBiddingReceiptDTO fpBiddingReceiptDto,
			JSONArray jsonArray, ResultMap result,ProductDetailPageDTO productDetailView) throws Exception {
		//返佣金额  仅支持两位小数,  错误直接返回  校验不通过
		for (int j = 0; j < jsonArray.size();j++) {
			try {
				JSONObject object = jsonArray.getJSONObject(j);
				BigDecimal bigDecimal = object.getBigDecimal("rebate");
				if(!bigDecimal.toString().matches("\\d+(\\.\\d{1,2})?")){//返佣金额是数字  且最多两位小数
					result.setStatus(STATUS.ERROR);
					result.setStatusCode(ResultMap.STATUS_CODE_REBATE_TWO);
					return ;
				}
			}catch (Exception e) {
				log.info("rebate error");
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_REBATE_TWO);
				return ;
			}
		}
		if (productDetailView == null
				|| productDetailView.getProductId() == null) {
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PROTYPE_NOT_EXIST);
			return ;
		}
		//是否允许竞价
		Boolean flagBidding=productDetailView.getFlagBidding();
		if(!flagBidding){
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_CANNOT_BID);
			return ;
		}
		//协议价 不能竞价
		List<ProductProfitAndRebateVO> profitAndRebateList = productDetailView.getProfitAndRebateList();
		for (ProductProfitAndRebateVO productProfitAndRebateVO : profitAndRebateList) {
			if("1".equals(productProfitAndRebateVO.getpIsAgreement())){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_REBATE_ISAGREEMENT);
				return ;
			}
		}
		// 查询产品 竞价 收益
		FpBiddingReceiptDTO dto = new FpBiddingReceiptDTO();
		dto.setpId(fpBiddingReceiptDto.getpId());
		dto.setBiddingStatus("3");
		List<Map<String, Object>> fpBiddingReceiptList = fpBiddingReceiptService
				.queryFpBiddingReceipt(dto);
		
		//没有承销价格，查询 官网价格
		if(fpBiddingReceiptList==null||fpBiddingReceiptList.size()==0){
			fpBiddingReceiptList = fpBiddingReceiptService.queryFpCurrentAnune(fpBiddingReceiptDto);
		}
		
		// 与当前收益比较
		// [{id:1,rebate:1.5},{},{}]
		if (jsonArray.size() != fpBiddingReceiptList.size()
				&& jsonArray.size() > 0) {
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_REBATE_LOSE);
			return ;
		}
		
		int num = 0;
		boolean flag = false;// 是否存在一条记录大于
		BigDecimal bailAmount = new BigDecimal(0);
		for (Map<String, Object> fpBiddingReceipt : fpBiddingReceiptList) {
			int fpBiddingId = (int) Long.parseLong(fpBiddingReceipt
					.get("id") + "");
			BigDecimal pRabateProfit = (BigDecimal) fpBiddingReceipt
					.get("pRabateProfit");
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject object = jsonArray.getJSONObject(i);
				Integer id = object.getInteger("id");
				BigDecimal rebate  = object.getBigDecimal("rebate");
				if (id == fpBiddingId
						&& rebate.compareTo(pRabateProfit) >= 0) {
					num++;
					if (rebate.compareTo(pRabateProfit) > 0) {
						flag = true;
					}
					break;
				}
			}
		}
		// 必须每条佣金都不能小于竟网价格
		if (num != fpBiddingReceiptList.size()) {
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_REBATE_MIN);
			return ;
		}
		// 必须有一条记录大于竞网价格
		if (!flag) {
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_REBATE_ERROR);
			return ;
		}

		BigDecimal chajia = new BigDecimal(0);// 最高差价
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject object = jsonArray.getJSONObject(i);
			int id=object.getInteger("id");
			Map<String, Object> currentAnuneById = fpBiddingReceiptService.queryFpCurrentAnuneById(id);
			if(currentAnuneById.isEmpty()){
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_AMOUNT_ERROR);
				return ;
			}
			BigDecimal rebate = object.getBigDecimal("rebate");
			BigDecimal pRabateProfit = (BigDecimal) currentAnuneById.get("pRabateProfit");
			if (rebate.compareTo(pRabateProfit) >= 0) {
				if (rebate.compareTo(pRabateProfit) > 0) {
					BigDecimal c = rebate.subtract(pRabateProfit);
					if (chajia.compareTo(c) < 0) {
						chajia = c;
					}
				}
			}
		}
		
		//  按照300万基数进行 计算 根据最高差价 计算保证金
//			bailAmount = bailAmount.add(chajia.divide(new BigDecimal(100))
//					.multiply(new BigDecimal(3000000)));
		
		try {
			
			String bailAmoutScript="var a={bailAmount}; a/100*3000000";
			
			bailAmoutScript=bailAmoutScript.replace("{bailAmount}",chajia.toString());
			//保留两位小数
			bailAmount = new BigDecimal(CallJavaScriptUtil.evalScriptStr(bailAmoutScript)+"").setScale(2,BigDecimal.ROUND_HALF_UP);
		} catch (Exception e) {
			log.error("bailAmount error",e);
		}

		if (bailAmount.compareTo(new BigDecimal(0)) <= 0) {
			// 没有保证金
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_AMOUNT_ERROR);
			return ;
		}

		fpBiddingReceiptDto.setBailAmount(bailAmount);
		result.setAttribute("chajia", chajia);
		result.setAttribute("bailAmount", bailAmount);
		
	}

	/**
	 * 查询竞价收单
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/queryBiddingReceipt")
	@ResponseBody
	public ResultMap queryBiddingReceipt(HttpServletRequest request,
			HttpServletResponse response, String pId) {
		ResultMap result = new ResultMap();

		// 产品id不能为空
		if (StringUtils.isBlank(pId) || !pId.matches("\\d+")) {
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
			return result;
		}
		try {
			// 未登录 不看佣金
			UserDTO loginUser = SessionUtil.getSession().getUser();
			boolean flagLogin = SessionUtil.getSession().getLogin();

			FpBiddingReceiptDTO fpBiddingReceiptDto = new FpBiddingReceiptDTO();
			fpBiddingReceiptDto.setpId(Integer.parseInt(pId));
			// 成功状态
			fpBiddingReceiptDto.setBiddingStatus("3");
			// 承销人信息
			Map<String, Object> queryBiddingReceiptUserInfo = fpBiddingReceiptService
					.queryBiddingReceiptUserInfo(fpBiddingReceiptDto);
			if (queryBiddingReceiptUserInfo == null
					|| queryBiddingReceiptUserInfo.isEmpty()) {
				result.setAttribute("hasBiddingReceitUser", false);
			} else {
				result.setAttribute("hasBiddingReceitUser", true);
				if ("1".equals(queryBiddingReceiptUserInfo.get("flagAnonymous"))) {
					// 匿名
					queryBiddingReceiptUserInfo.put("uName", "匿名用户");
					// queryBiddingReceiptUserInfo.put("uMobile",
					// StringUtil.mobileHide4Number(queryBiddingReceiptUserInfo.get("uMobile")+""));
				}
				// 已登录 并且是当前人 展示放弃竞价id
				String loginId = flagLogin?loginUser.getId().toString():"";
				String userId = queryBiddingReceiptUserInfo.get("userId") + "";
				if (flagLogin&& loginId.equals(userId)) {
					queryBiddingReceiptUserInfo.remove("userId");
					queryBiddingReceiptUserInfo.put("currentBiddingIsLogin",true);
				} else {
					queryBiddingReceiptUserInfo.remove("userId");
					queryBiddingReceiptUserInfo.remove("biddingReceiptId");
				}
				result.setAttribute("biddingReceiptUserInfo",
						queryBiddingReceiptUserInfo);
			}

			// 查询当前产品承销价格
			List<Map<String, Object>> productAnueList = fpBiddingReceiptService
					.queryFpBiddingReceipt(fpBiddingReceiptDto);
			//没有承销价格，查询 官网价格
			if(productAnueList.size()==0){
				productAnueList = fpBiddingReceiptService.queryFpCurrentAnune(fpBiddingReceiptDto);
			}
			
			// 排序
			Collections.sort(productAnueList,
					new Comparator<Map<String, Object>>() {
						@Override
						public int compare(Map<String, Object> o1,
								Map<String, Object> o2) {
							BigDecimal pStartAmount = (BigDecimal) o1
									.get("pStartAmount");
							BigDecimal pStartAmount2 = (BigDecimal) o2
									.get("pStartAmount");
							return pStartAmount.compareTo(pStartAmount2);
						}
					});
			
			//拼描述       如果登录为空     设置 返佣为null
			String role =flagLogin?loginUser.getRole():"";
			boolean flag=!flagLogin||loginUser == null||"1".equals(role) || "99".equals(role) || "98".equals(role);
			for (Map<String, Object> map : productAnueList) {
				BigDecimal pStartAmount = (BigDecimal) map
						.get("pStartAmount");
				BigDecimal pStartAmount2 = (BigDecimal) map
						.get("pEndAmount");
				map.put("amountDesc", pStartAmount.divide(new BigDecimal(10000)).intValue()+"-"+pStartAmount2.divide(new BigDecimal(10000)).intValue()+"万");
				if (flag) {
					map.put("pRabateProfit", null);
				}
			}

			result.setAttribute("productAnueList", productAnueList);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("queryBiddingReceipt error", e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}

		return result;

	}

	/**
	 * 放弃竞价收单
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/dropBiddingReceipt")
	@ResponseBody
	public ResultMap dropBiddingReceipt(HttpServletRequest request,
			HttpServletResponse response, String biddingReceiptId) {
		ResultMap result = new ResultMap();

		try {
			if (StringUtils.isBlank(biddingReceiptId)) {
				result.setStatus(STATUS.ERROR);
				result.setStatusCode(ResultMap.STATUS_CODE_PARAMETERS_LOSE);
				return result;
			}

			// 查询当前竞价 是否属于该用户
			FpBiddingReceiptDTO fpBiddingReceiptDto = new FpBiddingReceiptDTO();
			fpBiddingReceiptDto.setId(Integer.parseInt(biddingReceiptId));
			// 成功状态
			fpBiddingReceiptDto.setBiddingStatus("3");
			// 承销人信息
			Map<String, Object> queryBiddingReceiptUserInfo = fpBiddingReceiptService
					.queryBiddingReceiptUserInfo(fpBiddingReceiptDto);

			// 信息不存在
			if (queryBiddingReceiptUserInfo == null
					|| queryBiddingReceiptUserInfo.isEmpty()) {
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
				return result;
			}
			UserDTO loginUser = SessionUtil.getSession().getUser();
			String userId = loginUser.getId().toString();
			String biddingUserId = queryBiddingReceiptUserInfo.get("userId") + "";
			if (userId.equals(biddingUserId)) {
				// 本人 放弃承销
				fpBiddingReceiptDto.setBiddingStatus("5");
				fpBiddingReceiptDto.setBiddingFailDate(System.currentTimeMillis()+"");
				DTOdateSetUtil.setUpdateInfo(fpBiddingReceiptDto);
				fpBiddingReceiptService
						.updateBiddingReceipt(fpBiddingReceiptDto);
				try {
					int pId=(Integer) queryBiddingReceiptUserInfo.get("pId");
					// 查询产品是否存在
					ProductDetailPageDTO productDetailView = productService
							.getProductDetailPage(pId);
					List<String> mobileList=new ArrayList<String>();
					for (String phone : biddingProductPhoneTo.split(";")) {
						if(!StringUtils.isBlank(phone.trim()))
							mobileList.add(phone);
					}
					UserDTO user=SessionUtil.getSession().getUser();
					//发送短信和邮件
					String content="%s用户放弃承销【%s】产品，该用户手机号码%s.";
					String userName=StringUtils.isBlank(user.getuRealName())?user.getLoginName():user.getuRealName();
					content=String.format(content,userName,productDetailView.getProductName(),user.getLoginName());
					smsNewService.sendSms(mobileList,content,"smsSendSwitch");
					
					//发送邮件
					MailContentDTO mail = new MailContentDTO();
					mail.setRecAddress( biddingProductEmailTo);
					mail.setCc( biddingProductEmailCopyTo);
					mail.setSubject("用户放弃承销");
					mail.setContext(content);
					mailSenderService.send(mail);
				} catch (Exception e) {
					log.error("上传产品发送短信,邮件异常",e);
				}
				
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			} else {
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_OPERATE_ERROE);
				return result;
			}
		} catch (Exception e) {
			log.error("dropBiddingReceipt error", e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
			return result;
		}
		return result;
	}

}
